/**
 * 文章导出工具类
 * 支持导出为 Markdown 格式
 */

import { saveAs } from 'file-saver'

export interface Article {
  id: string
  title: string
  content: string
  htmlContent?: string
  author: string
  publishDate: string
  tags?: string[]
  category?: string
  excerpt?: string
}

export interface ExportOptions {
  filename?: string
  includeMetadata?: boolean
}

/**
 * 文章导出器类
 */
export class ArticleExporter {
  /**
   * 导出为 Markdown 格式
   */
  static async exportToMarkdown(article: Article, options: ExportOptions = {}): Promise<void> {
    try {
      const { filename = `${article.title}.md`, includeMetadata = true } = options

      let markdown = ''

      // 添加元数据
      if (includeMetadata) {
        markdown += '---\n'
        markdown += `title: "${article.title}"\n`
        markdown += `author: "${article.author}"\n`
        markdown += `date: "${article.publishDate}"\n`

        if (article.category) {
          markdown += `category: "${article.category}"\n`
        }

        if (article.tags && article.tags.length > 0) {
          markdown += `tags: [${article.tags.map((tag) => `"${tag}"`).join(', ')}]\n`
        }

        if (article.excerpt) {
          markdown += `excerpt: "${article.excerpt}"\n`
        }

        markdown += '---\n\n'
      }

      // 添加标题
      markdown += `# ${article.title}\n\n`

      // 添加作者和日期信息
      if (includeMetadata) {
        markdown += `**作者**: ${article.author}  \n`
        markdown += `**发布时间**: ${new Date(article.publishDate).toLocaleDateString('zh-CN')}  \n\n`

        if (article.tags && article.tags.length > 0) {
          markdown += `**标签**: ${article.tags.map((tag) => `\`${tag}\``).join(' ')}\n\n`
        }
      }

      // 添加内容
      markdown += article.content

      // 创建并下载文件
      const blob = new Blob([markdown], { type: 'text/markdown;charset=utf-8' })
      saveAs(blob, filename)

      console.log('✅ Markdown 导出成功')
    } catch (error) {
      console.error('❌ Markdown 导出失败:', error)
      throw new Error('Markdown 导出失败')
    }
  }
}

/**
 * 导出工具函数
 */
export const exportUtils = {
  /**
   * 快速导出 Markdown
   */
  markdown: (article: Article, options?: ExportOptions) =>
    ArticleExporter.exportToMarkdown(article, options),
}

export default ArticleExporter
